/*
 * This source code is part of TWaver 4.0
 *
 * Serva Software PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * Copyright 2002 - 2011 Serva Software. All rights reserved.
 */

package demo.network.topo.matrix;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.List;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import demo.DemoPane;
import demo.DemoUtil;

import twaver.AlarmSeverity;
import twaver.BaseEquipment;
import twaver.DataBoxQuickFinder;
import twaver.Element;
import twaver.EllipseGroup;
import twaver.Generator;
import twaver.Link;
import twaver.TDataBox;
import twaver.TWaverConst;
import twaver.TWaverUtil;
import twaver.VisibleFilter;
import twaver.Node;
import twaver.network.PaintAttachmentFilter;
import twaver.network.TNetwork;
import twaver.network.ui.Attachment;

public class MatrixDemo extends DemoPane {

	public final static String BUSINESSID = "businessID";

    TDataBox box = new TDataBox();
    TNetwork network = new TNetwork(box);
    JButton button = new JButton("Press me to start...");
    JCheckBox hideLink = new JCheckBox("", false);
    JCheckBox hideLabel = new JCheckBox("", false);
    JCheckBox hideAlarm = new JCheckBox("", false);
    JTextField findBID = new JTextField();
    JTextField findTAG = new JTextField();

    private VisibleFilter linkFilter = new VisibleFilter(){
		public boolean isVisible(Element element) {
			if(hideLink.isSelected() && element instanceof Link){
				return false;
			}
			return true;
		}
    };

    private Generator labelGenerator = new Generator(){
		public Object generate(Object object) {
			if(hideLabel.isSelected()){
				return null;
			}else if(object instanceof BaseEquipment){
				BaseEquipment equipment = ((BaseEquipment)object);
				return "Tag" + "(" + equipment.getTag() + ") * (" + equipment.getClientProperty(BUSINESSID) + ")";
			}else{
				return ((Element)object).getName();
			}
		}
    };

    private DataBoxQuickFinder finder = box.createClientPropertyFinder(BUSINESSID);

    public MatrixDemo() {
    	network.setTextureBackground("/demo/resource/images/snowflake.png");
    	network.setToolbarByName(TWaverConst.DEFAULT_TOOLBAR);
    	network.getToolbar().add(new GroupButton(network));
    	network.setElementLabelGenerator(labelGenerator);
    	network.addVisibleFilter(linkFilter);
      	network.clearMovableFilters();
		network.setEnableDeleteWithKeyboard(true);
       this.network.getDefaultOverview().getOverviewPane().setPaintAttachmentFilter(new PaintAttachmentFilter(){
			public boolean isPaintable(Attachment attachment) {
				return false;
			}
        });
	       
      	DemoUtil.createInternalFrame("Quick Search", network, createControlPanel());
      	
        this.add(network, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
        button.setBackground(Color.YELLOW);
        button.setForeground(Color.BLACK);
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                test();
            }
        });
        createElements(false);
        network.getZoomer().zoomToOverview();
    }

    public JPanel createControlPanel(){
    	JPanel controlPanel = new JPanel();
    	controlPanel.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    	controlPanel.setLayout(new GridLayout(5, 2));
    	hideLink.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				network.getCanvas().repaint();
			}
    	});
    	hideLabel.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				network.getCanvas().repaint();
				network.invalidateAllElementBounds();
			}
    	});
    	hideAlarm.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				network.setAlarmBalloonVisible(!hideAlarm.isSelected());
			}
    	});
    	findBID.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				try {
					box.getSelectionModel().clearSelection();
					int businessID;
					String text = findBID.getText();
					businessID = Integer.parseInt(text);
					List elements = finder.find(new Integer(businessID));
					box.getSelectionModel().setSelection(elements);
					if(elements.size() > 0){
						network.centerElement((Element)elements.get(0));
					}
				} catch (Exception ex) {
				}
			}
    	});
    	findTAG.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				try {
					box.getSelectionModel().clearSelection();
					String text = findTAG.getText();
					Element element = box.getElementByTag(text);
					if(element != null){
						box.getSelectionModel().setSelection(element);
						network.centerElement(element);
					}
				} catch (Exception ex) {
				}
			}
    	});
    	controlPanel.add(new JLabel("Find BID"));
    	controlPanel.add(findBID);
    	controlPanel.add(new JLabel("Find TAG"));
    	controlPanel.add(findTAG);
    	controlPanel.add(new JLabel("Hide Link"));
    	controlPanel.add(hideLink);
    	controlPanel.add(new JLabel("Hide Label"));
    	controlPanel.add(hideLabel);
    	controlPanel.add(new JLabel("Hide Alarm"));
    	controlPanel.add(hideAlarm);
    	

    	return controlPanel;
    }

    public void createElements(boolean showMessage){
        int x = 10, y = 10;
        int gap = 125;

        //create nodes
        int counter = 0;
        long time = System.currentTimeMillis();
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
            	BaseEquipment node = new BaseEquipment("node-" + i + "-" + j);
            	node.putCustomDraw(true);
            	node.putCustomDrawFillColor(Color.ORANGE);
                node.setTag(i * x + j + "");
                node.putClientProperty("businessID", new Integer(TWaverUtil.getRandomInt(100)));
                node.setLocation(gap * (i + 1), gap * (j + 1));
                node.putLabelColor(Color.BLUE);
                box.addElement(node);
                counter++;
            }
        }
        if(showMessage){
            JOptionPane.showMessageDialog(this,
                    "Create " + counter +
                    " nodes, time cost: " +
                    (System.currentTimeMillis() - time) + " ms");
        }

        time = System.currentTimeMillis();
        counter = 0;
        Integer linkWidth = new Integer(5);
        //create links.
        for (int i = 0; i < x; i++) {
            for (int j = 0; j < y; j++) {
                if (i > 0) {
                    Node from = (Node) box.getElementByID("node-" + i + "-" + j);
                    Node to = (Node) box.getElementByID("node-" + (i - 1) + "-" + j);
                    Link link = new Link(from, to);
                    link.putLinkWidth(linkWidth.intValue());
                    link.putLinkColor(Color.GREEN);
                    box.addElement(link);
                    counter++;
                }
                if (j > 0) {
                    Node from = (Node) box.getElementByID("node-" + i + "-" + j);
                    Node to = (Node) box.getElementByID("node-" + i + "-" + (j - 1));
                    Link link = new Link(from, to);
                    link.putLinkWidth(linkWidth.intValue());
                    link.putLinkColor(Color.GREEN);
                    box.addElement(link);
                    counter++;
                }
            }
        }
        if(showMessage){
	        JOptionPane.showMessageDialog(this,
	                                      "Create " + counter +
	                                      " links, time cost: " +
	                                      (System.currentTimeMillis() - time) + " ms");
        }
    }

    private void test() {
        box.clear();

        createElements(true);

        //change alarm state for each element.
        long time = System.currentTimeMillis();
        int counter = 0;
        //raise alarms.
        Iterator it = box.iterator(Node.class);
        while (it.hasNext()) {
            Element element = (Element) it.next();
            element.getAlarmState().addNewAlarm(AlarmSeverity.CRITICAL);
            counter++;
        }
        JOptionPane.showMessageDialog(this,
                                      "Raise alarm for " + counter +
                                      " elements, time cost: " +
                                      (System.currentTimeMillis() - time) + " ms");
        //clear alarms.
        time = System.currentTimeMillis();
        counter = 0;
        it = box.iterator(Node.class);
        while (it.hasNext()) {
            Element element = (Element) it.next();
            element.getAlarmState().clear();
            counter++;
        }
        JOptionPane.showMessageDialog(this,
                                      "Clear alarm state for " + counter +
                                      " elements, time cost: " +
                                      (System.currentTimeMillis() - time) + " ms");

        int returnVal = JOptionPane.showConfirmDialog(network, "do you want to clear box?",
        		"clear box", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
        if (returnVal != JOptionPane.NO_OPTION) {
            //clear box.
            time = System.currentTimeMillis();
            box.clear();
            JOptionPane.showMessageDialog(this,
                                          "Clear data box, time cost: " +
                                          (System.currentTimeMillis() - time) + " ms");
        }

    }

}

class GroupButton extends JButton {
    public GroupButton(final TNetwork network) {
        this.setText("");
        this.setIcon(TWaverUtil.getImageIcon("/resource/image/twaver/ellipseGroup_icon.png"));
        this.setMargin(TWaverConst.NONE_INSETS);
        this.addActionListener(new ActionListener(){
			public void actionPerformed(ActionEvent e) {
				TDataBox box = network.getDataBox();
				if(box.getSelectionModel().size() == 0){
					JOptionPane.showMessageDialog(network, "you should select some nodes firstly.");
				}else{
					EllipseGroup group = new EllipseGroup();
					group.putGroupFillColor(TWaverUtil.getRandomColor());
                    group.putGroupEllipse3D(TWaverUtil.getRandomBool());
                    group.putGroupOpaque(true);
					network.getDataBox().addElement(group);
					group.setExpand(false);

					Iterator it = box.selection();
					while(it.hasNext()){
						Element element = (Element)it.next();
						if(element instanceof Link){
							continue;
						}
						group.addChild(element);
					}
				}

			}
        });
    }
}